package cloud.pangui.core.utils;

import java.util.HashMap;
import java.util.Map;

/**
 * 提供全局式的线程变量
 * @Auther hepangui
 * @Date 2020/11/5 0005
 */
public class ThreadLocalUtils {
	private static ThreadLocal<Map<String, Object>> threadLocal = new ThreadLocal<>();

	/**
	 * 根据key获取value
	 *
	 * @param key
	 * @return
	 */
	public static Object get(String key) {
		Map<String, Object> stringObjectMap = threadLocal.get();
		if (stringObjectMap == null) {
			return null;
		}
		return stringObjectMap.get(key);
	}

	/**
	 * 存放一个key，value
	 *
	 * @param key
	 * @param value
	 */
	public static void put(String key, Object value) {
		Map<String, Object> stringObjectMap = threadLocal.get();
		if (stringObjectMap == null) {
			stringObjectMap = new HashMap<>();
			threadLocal.set(stringObjectMap);
		}
		stringObjectMap.put(key, value);
	}

	/**
	 * 是否含有指定Key
	 *
	 * @param key
	 */
	public static boolean contains(Object key) {
		Map<String, Object> stringObjectMap = threadLocal.get();
		if (stringObjectMap == null) {
			return false;
		}
		return stringObjectMap.containsKey(key);
	}

	/**
	 * 移除指定的key
	 *
	 * @param key
	 */
	public static void remove(String key) {
		Map<String, Object> stringObjectMap = threadLocal.get();
		if (stringObjectMap != null) {
			stringObjectMap.remove(key);
		}
	}
}
